<?php
declare (strict_types=1);

namespace app\course\logic\classes\admin;

use app\admin\logic\system\Log;
use app\common\exception\LogicException;
use app\course\model\base\Course;
use app\course\model\classes\admin\ClassesLink as ClassesLinkModel;

/**
 * 后台管理逻辑层
 */
class ClassesLink extends ClassesLinkModel
{
    /**
     * 关联列表
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-29
     *
     * @return   [type]                         [description]
     */
    public function getList(int $classes_id, ?string $title = '')
    {
        return $this->alias('ClassesLink')->where('classes_id', $classes_id)->hasWhere('course', [['title', 'like', '%' . $title . '%']])->with(['course'])->paginate($this->getListRows());
    }

    /**
     * 添加关联课程
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-29
     *
     * @return   [type]                         [description]
     */
    public function addClassesLink(int $classes_id, array $data = [])
    {
        $data['classes_id'] = $classes_id;

        // 验证数据
        $this->getValidate()->failException()->check($data);

        if (!$this->data($data, true)->save()) throw new LogicException('添加失败');

        $courseTitle  = app(Course::class)->where('id', $data['course_id'])->value('title');
        $classesTitle = app(Course::class)->where('id', $classes_id)->value('title');
        Log::write('将课程【' . $courseTitle . '】关联到班级课【' . $classesTitle . '】');

        return $this;
    }

    /**
     * 移除
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-29
     *
     * @param int $id [description]
     * @return   [type]                             [description]
     */
    public function deleteClassesLink(int $id)
    {
        $link = $this->where('id', $id)->findOrFail();

        if (!$link->delete()) {
            throw new LogicException('移除失败');

        }

        $courseTitle  = app(Course::class)->where('id', $link->course_id)->value('title');
        $classesTitle = app(Course::class)->where('id', $link->classes_id)->value('title');
        Log::write('将课程【' . $courseTitle . '】从班级课【' . $classesTitle . '】中移除');
    }
}
